part of '../version.dart';

/// major.minor.patch，比如1.0.0
class Version {
  int major;
  int minor;
  int patch;

  Version(this.major, this.minor, this.patch);

  /// 解析字符串
  factory Version.parse(String input) {
    // 分割字符串
    List<String> parts = input.split('.');
    if (parts.length < 2 || parts.length > 3) {
      throw Bug("版本号应该用'.'隔开，至少有2到3位，并且每一位都是非负整数");
    }
    // 解析版本号
    int major = int.parse(parts[0]);
    int minor = int.parse(parts[1]);
    int patch = parts.length == 3 ? int.parse(parts[2]) : 0; // 如果只有两位，则默认第三位为0
    return Version(major, minor, patch);
  }

  /// 测试版本是否兼容，major和minor相同就算是兼容
  bool isCompatible(Version other) =>
      major == other.major && minor == other.minor;

  @override
  String toString() => "$major.$minor.$patch";

  /// 进行一些小修改然后返回修改后的版本
  Version copyWith({int? major, int? minor, int? patch}) => Version(
        major ?? this.major,
        minor ?? this.minor,
        patch ?? this.patch,
      );

  @override
  bool operator ==(Object other) {
    if (other is Version) {
      return major == other.major &&
          minor == other.minor &&
          patch == other.patch;
    }
    return false;
  }

  @override
  int get hashCode => Object.hash(major, minor, patch);

  int compareTo(Version other) {
    if (major != other.major) {
      return major.compareTo(other.major);
    }
    if (minor != other.minor) {
      return minor.compareTo(other.minor);
    }
    return patch.compareTo(other.patch);
  }

  bool operator <(Version other) => compareTo(other) < 0;

  bool operator >(Version other) => compareTo(other) > 0;

  bool operator <=(Version other) => compareTo(other) <= 0;

  bool operator >=(Version other) => compareTo(other) >= 0;
}
